﻿using PhoneStoreWeb.Models;
using System;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

namespace PhoneStoreWeb.Controllers
{
    [HandleError]
    public class AccountController : Controller
    {
        public IFormsAuthenticationService FormsService { get; set; }

        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null)
            {
                FormsService = new FormsAuthenticationService();
            }
            if (MembershipService == null)
            {
                MembershipService = new MembershipService();
            }
            base.Initialize(requestContext);
        }

        // URL: /Account/Unauthorized
        public ActionResult Unauthorized()
        {
            return View();
        }

        public ActionResult LogIn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogIn(LogInModel model, string returnUrl)
        {
            if (User.Identity != null && User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Unauthorized", "Account");
            }
            if (!String.IsNullOrEmpty(model.UserName) && !String.IsNullOrEmpty(model.Password))
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    MvcApplication.NumberOfUsersOnline++;
                    ShoppingCartModel.ResetCartSessionKey(this.HttpContext);
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
            }
            // If we got this far, something failed, redisplay form
            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOut()
        {
            FormsService.SignOut();
            MvcApplication.NumberOfUsersOnline--;
            ShoppingCartModel.ResetCartSessionKey(this.HttpContext);
            return RedirectToAction("Index", "Home", new { area = "" });
        }

        public ViewResult Register()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    // Migrate to cart
                    if (model.MigrateToCart)
                    {
                        ShoppingCartController.MigrateCart(this.HttpContext, model.UserName);
                    }
                    MembershipService.SendConfirmationEmail(model.UserName);
                    return RedirectToAction("RegisterConfirmation");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }
            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        public ActionResult RegisterConfirmation()
        {
            return View();
        }

        public ActionResult Welcome()
        {
            return View();
        }

        public ActionResult RegisterEmail(string id)
        {
            if (string.IsNullOrEmpty(id) || (!Regex.IsMatch(id, @"[0-9a-f]{8}\-([0-9a-f]{4}\-){3}[0-9a-f]{12}")))
            {
                TempData["tempMessage"] = "Tài khoản chưa được xác nhận. Xin hãy xác nhận tài khoản qua email mà chúng tôi đã cung cấp.";
                return View();
            }
            else
            {
                MembershipUser user = Membership.GetUser(new Guid(id));
                if (!user.IsApproved)
                {
                    user.IsApproved = true;
                    Membership.UpdateUser(user);
                    FormsService.SignIn(user.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Welcome");
                }
                else
                {
                    FormsService.SignOut();
                    TempData["tempMessage"] = "Quý khách đã xác nhận tài khoản rồi. Xin vui lòng đăng nhập";
                    return RedirectToAction("LogOn");
                }
            }
        }

        [Authorize]
        public ViewResult ChangePassword()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    FormsService.SignOut();
                    return RedirectToAction("ChangePasswordSuccessfully");
                }
                else
                {
                    ModelState.AddModelError("", "Mật khẩu hiện tại không đúng hoặc mật khẩu mới không hợp lệ.");
                }
            }
            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        public ViewResult ChangePasswordSuccessfully()
        {
            return View();
        }

        public ViewResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ForgotPassword(string username)
        {
            ViewBag.ResetPasswordEmail = MembershipService.SendResetPasswordEmail(username);
            return View("ForgotPasswordConfirmation");
        }

        public ActionResult ResetPasswordEmail(string id)
        {
            if (string.IsNullOrEmpty(id) || (!Regex.IsMatch(id, @"[0-9a-f]{8}\-([0-9a-f]{4}\-){3}[0-9a-f]{12}")))
            {
                TempData["tempMessage"] = "Mật khẩu chưa được khôi phục. Xin hãy khôi phục mật khẩu qua email mà chúng tôi đã cung cấp.";
                return View();
            }
            else
            {
                MembershipUser user = Membership.GetUser(new Guid(id));
                return RedirectToAction("ResetPassword", new { username = user.UserName });
            }
        }

        public ViewResult ResetPassword(string username)
        {
            ViewBag.UserName = username;
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult ResetPassword(ResetPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                MembershipUser user = Membership.GetUser(model.UserName);
                user.ChangePassword(user.GetPassword(), model.NewPassword);
                Membership.UpdateUser(user);
                return RedirectToAction("ResetPasswordSuccessfully");
            }
            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        public ViewResult ResetPasswordSuccessfully()
        {
            return View();
        }
        
        public ActionResult Visitors()
        {
            ViewBag.NumberOfUsers = Membership.GetAllUsers().Count;
            return View();
        }
    }
}